package com.pcbly.web.components.form;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.HashMap;
import java.util.Set;

import org.apache.log4j.Logger;

import com.pcbly.web.bean.field.FormTableDataBean;
import com.pcbly.web.bean.table.ColumnBean;
import com.pcbly.web.bean.table.TableBean;
import com.pcbly.web.business.form.MacroComponentService;
import com.pcbly.web.components.utils.LightsoftStringUtils;

public class AnalyseHtml implements java.io.Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2551093431324346100L;

	private static Logger _log = Logger.getLogger(AnalyseHtml.class);

	private List<FormTableDataBean> tableDataBeans;

	private List<HashMap<String, HashMap<String, String>>> tableDatas;

	private String element;

	private List<String> idtandclist;

	private List<String> tandclist;

	private List<ColumnBean> columnBeans;

	private List<TableBean> tableBeans;

	private MacroComponentService macroComponentService;

	public List<FormTableDataBean> getTableDataBeans() {
		return tableDataBeans;
	}

	public void setTableDataBeans(List<FormTableDataBean> tableDataBeans) {
		this.tableDataBeans = tableDataBeans;
	}

	public List<ColumnBean> getColumnBeans() {
		return columnBeans;
	}

	public void setColumnBeans(List<ColumnBean> columnBeans) {
		this.columnBeans = columnBeans;
	}

	public List<TableBean> getTableBeans() {
		return tableBeans;
	}

	public void setTableBeans(List<TableBean> tableBeans) {
		this.tableBeans = tableBeans;
	}

	public MacroComponentService getMacroComponentService() {
		return macroComponentService;
	}

	public void setMacroComponentService(
			MacroComponentService macroComponentService) {
		this.macroComponentService = macroComponentService;
	}

	public List<String> getIdtandclist() {
		return idtandclist;
	}

	public void setIdtandclist(List<String> idtandclist) {
		this.idtandclist = idtandclist;
	}

	public List<String> getTandclist() {
		return tandclist;
	}

	public void setTandclist(List<String> tandclist) {
		this.tandclist = tandclist;
	}

	public String getElement() {
		return element;
	}

	public String getHtml() throws Exception {
		String testring = element;
		try {
			List<String> tlist = new ArrayList<String>();
			HtmlElementComponents html = new HtmlElementComponents();
			html.setElement(element);
			List<String> list = html.indexHtml();
			List<String> rlist = new ArrayList<String>();
			for (String single : list) {// 解析表单的元素 例如：input,textarea等
				StringBuilder sb = new StringBuilder();
				if (single.indexOf("input") > 0) {
					if (single.indexOf("button") > 0) {
						sb.append(single);
					} else {
						sb.append(getInput(single));
					}
				} else if (single.indexOf("textarea") > 0) {
					sb.append(getTextarea(single));

				} else if (single.indexOf("select") > 0) {
					sb.append(getSelect(single));
				}
				tlist.add(sb.toString());
			}
			for (String string : tlist) { // 取代以id_开头定义的name or id
				for (int i = 0; i < idtandclist.size(); i++) {
					if (string.indexOf(idtandclist.get(i)) >= 0) {
						string = string.replaceAll(idtandclist.get(i),
								tandclist.get(i));
						break;
					}
				}
				rlist.add(string);
			}

			testring = testring.replaceAll("\\s*<\\s*form[^>]*>", "");
			testring = testring.replaceAll("\\s*<\\s*/\\s*form\\s*>", "");
			for (int i = 0; i < rlist.size(); i++) {// 替换处理过的数据
				String rstring = rlist.get(i);
				String string = list.get(i);

				string = string.replaceAll("\\{", "\\\\{");
				string = string.replaceAll("\\[", "\\\\[");
				string = string.replaceAll("\\(", "\\\\(");
				testring = testring.replaceAll(string, rstring);
			}
		} catch (Exception e) {
			e.printStackTrace();
			_log.error(e.getMessage());
		}
		return testring;
	}

	public void setElement(String element) {
		this.element = element;
	}

	protected StringBuilder getMiddleProperty(String single, String reg,
			String cond) {
		StringBuilder sb = new StringBuilder();
		String celement = LightsoftStringUtils.patternSingleRegStringToArray(
				single, reg);
		if (!(celement == null || "".equals(celement.trim()))) {
			sb.append(" ");
			sb.append(cond);
			sb.append("=\"");
			sb.append(celement);
			sb.append("\" ");
		}
		return sb;
	}

	protected StringBuilder getTextarea(String single) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("<textarea ");

		String table;
		String celement = LightsoftStringUtils.patternSingleRegStringToArray(
				single, "table=(\"[^\"]*\")");
		sb.append(" table=\"");
		sb.append(celement);
		sb.append("\" ");
		table = celement;

		sb.append(getMiddleProperty(single, "style=(\"[^\"]*\")", "style"));
		sb.append(getMiddleProperty(single, "size=(\"[^\"]*\")", "size"));
		sb.append(getMiddleProperty(single, "class=(\"[^\"]*\")", "class"));
		sb.append(getMiddleProperty(single, "rows=(\"[^\"]*\")", "rows"));
		sb.append(getMiddleProperty(single, "cols=(\"[^\"]*\")", "cols"));

		celement = LightsoftStringUtils.patternSingleRegStringToArray(single,
				"name=(\"[^\"]*\")");
		String columnName = "";
		for (ColumnBean columnBean : columnBeans) {
			if (table.equals(columnBean.getTableBean().getId())
					&& celement.equals(columnBean.getId())) {
				columnName = columnBean.getColumnName();
				break;
			}
		}
		sb.append(" name=\"");
		sb.append(columnName);
		sb.append("_");
		sb.append(table);
		sb.append("_");
		sb.append(celement);
		sb.append("\" ");
		sb.append(" id=\"");
		sb.append(columnName);
		sb.append("_");
		sb.append(table);
		sb.append("_");
		sb.append(celement);
		sb.append("\" ");

		sb.append(elementProperty(table, celement));

		celement = LightsoftStringUtils.patternSingleRegStringToArray(single,
				"datafld=(\"[^\"]*\")");
		if (tableDatas==null||tableDatas.isEmpty()) {
			if (!(celement == null || "".equals(celement.trim()))) {
				table = LightsoftStringUtils.patternSingleRegStringToArray(single,
						"datasrc=(\"[^\"]*\")");
				if (!(table == null || "".equals(table.trim()))) {
					sb.append(" >");
					sb.append(toDefaultValueBySingleSql(table));
					sb.append("</textarea> ");
				} else {
					sb.append(" >");
					sb.append(toDefaultValue(celement));
					sb.append("</textarea> ");
				}
			} else
				sb.append("></textarea> ");
		}else{
			String value="";
			for(HashMap<String, HashMap<String, String>> map:tableDatas){
				Set<String> set=map.keySet();
				Iterator<String> it=set.iterator();
				while(it.hasNext()){
					if(it.next().equals(table)){
						HashMap<String,String> map1=map.get(table);
						value=map1.get(columnName);
						break;
					}
				}
			}
			sb.append(">");
			sb.append(value);
			sb.append("</textarea>");
		}
		return sb;
	}

	protected StringBuilder getSelect(String single) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("<select ");

		String table;
		String celement = LightsoftStringUtils.patternSingleRegStringToArray(
				single, "table=(\"[^\"]*\")");
		sb.append(" table=\"");
		sb.append(celement);
		sb.append("\" ");
		table = celement;

		sb.append(getMiddleProperty(single, "style=(\"[^\"]*\")", "style"));
		sb.append(getMiddleProperty(single, "size=(\"[^\"]*\")", "size"));
		sb.append(getMiddleProperty(single, "class=(\"[^\"]*\")", "class"));
		sb
				.append(getMiddleProperty(single, "multiple=(\"[^\"]*\")",
						"multiple"));

		celement = LightsoftStringUtils.patternSingleRegStringToArray(single,
				"name=(\"[^\"]*\")");
		String columnName = "";
		for (ColumnBean columnBean : columnBeans) {
			if (table.equals(columnBean.getTableBean().getId())
					&& celement.equals(columnBean.getId())) {
				columnName = columnBean.getColumnName();
				break;
			}
		}
		sb.append(" name=\"");
		sb.append(columnName);
		sb.append("_");
		sb.append(table);
		sb.append("_");
		sb.append(celement);
		sb.append("\" ");
		sb.append(" id=\"");
		sb.append(columnName);
		sb.append("_");
		sb.append(table);
		sb.append("_");
		sb.append(celement);
		sb.append("\" ");

		sb.append(elementProperty(table, celement));

		celement = LightsoftStringUtils.patternSingleRegStringToArray(single,
				"datafld=(\"[^\"]*\")");
		if (!(celement == null || "".equals(celement.trim()))) {
			String sql = LightsoftStringUtils.patternSingleRegStringToArray(single,
					"datasrc=(\"[^\"]*\")");
			if (!(sql == null || "".equals(sql.trim()))) {
				sb.append(">");
				sb.append(toDefaultValueByMulSql(sql));
				sb.append("</select>");
			} else {
				sb.append(">");
				String subString = single.substring(0, single.indexOf(">") + 1);
				subString = single.replaceAll(subString, sb.toString());
				sb.delete(0, sb.length() - 1);
				sb.append(subString);
			}
		} else {
			sb.append(">");
			String subString = single.substring(0, single.indexOf(">") + 1);
//			System.out.println(subString);
			subString = single.replaceAll(subString, sb.toString());
//			System.out.println(subString);
			sb.delete(0, sb.length());
			sb.append(subString);
//			System.out.println(sb);
		}
		// System.out.println(sb);
		if (!(tableDatas==null||tableDatas.isEmpty())) {
			String value="";
			for(HashMap<String, HashMap<String, String>> map:tableDatas){
				Set<String> set=map.keySet();
				Iterator<String> it=set.iterator();
				while(it.hasNext()){
					if(it.next().equals(table)){
						HashMap<String,String> map1=map.get(table);
						value=map1.get(columnName);
						break;
					}
				}
			}
			if(!"".equals(value)){
				value="value=\""+value+"\"";
				String temp=sb.toString();
				temp=temp.replaceAll(value, value+" selected ");
				sb.delete(0, sb.length());
				sb.append(temp);
			}
		}
		return sb;
	}

	protected StringBuilder elementProperty(String tableId, String coumnId) {// 设置一些数据校验和数据实体，数据属性
		StringBuilder sb = new StringBuilder();
		// sb.append(" title=\"");
		for (TableBean tableBean : tableBeans) {
			if (tableBean.getId().equals(tableId)) {
				sb.append(" tableName=\"");
				sb.append(tableBean.getTableName());
				sb.append("\" ");
				// sb.append("_");
				break;
			}
		}
		for (ColumnBean columnBean : columnBeans) {
			if (tableId.equals(columnBean.getTableBean().getId())
					&& coumnId.equals(columnBean.getId())) {
				sb.append(" columnName=\"");
				sb.append(columnBean.getColumnName());
				sb.append("\" ");
				// sb.append("_");

				sb.append(" dataType=\"");
				sb.append(columnBean.getColumnType());
				sb.append("\" ");
				// sb.append("_");

				sb.append(" dataLength=\"");
				sb.append(columnBean.getLength());
				sb.append("\" ");

				break;
			}
		}
		return sb;
	}

	protected StringBuilder getInput(String single) throws Exception {// check
		// radio
		// text
		StringBuilder sb = new StringBuilder();
		sb.append("<input ");
		String table;
		String celement = LightsoftStringUtils.patternSingleRegStringToArray(
				single, "table=(\"[^\"]*\")");
		sb.append(" table=\"");
		sb.append(celement);
		sb.append("\" ");
		table = celement;

		sb.append(getMiddleProperty(single, "style=(\"[^\"]*\")", "style"));
		sb.append(getMiddleProperty(single, "size=(\"[^\"]*\")", "size"));
		sb.append(getMiddleProperty(single, "class=(\"[^\"]*\")", "class"));
		sb.append(getMiddleProperty(single, "type=(\"[^\"]*\")", "type"));

		celement = LightsoftStringUtils.patternSingleRegStringToArray(single,
				"name=(\"[^\"]*\")");
		String columnName = "";
		for (ColumnBean columnBean : columnBeans) {
			if (table.equals(columnBean.getTableBean().getId())
					&& celement.equals(columnBean.getId())) {
				columnName = columnBean.getColumnName();
				break;
			}
		}
		sb.append(" name=\"");
		sb.append(columnName);
		sb.append("_");
		sb.append(table);
		sb.append("_");
		sb.append(celement);
		sb.append("\" ");
		sb.append(" id=\"");
		sb.append(columnName);
		sb.append("_");
		sb.append(table);
		sb.append("_");
		sb.append(celement);
		sb.append("\" ");

		sb.append(elementProperty(table, celement));

		if (tableDatas==null||tableDatas.isEmpty()) {
			celement = LightsoftStringUtils.patternSingleRegStringToArray(
					single, "datafld=(\"[^\"]*\")");

			if (!(celement == null || "".equals(celement.trim()))) {
				table = LightsoftStringUtils.patternSingleRegStringToArray(
						single, "datasrc=(\"[^\"]*\")");
				if (!(table == null || "".equals(table.trim()))) {// 判断从数据库读取
					sb.append(" value=\"");
					sb.append(toDefaultValueBySingleSql(table));
					sb.append("\" ");
				} else {
					sb.append(" value=\"");
					sb.append(toDefaultValue(celement));
					sb.append("\" ");
				}
			}
		} else {
			String value="";
			for(HashMap<String, HashMap<String, String>> map:tableDatas){
				Set<String> set=map.keySet();
				Iterator<String> it=set.iterator();
				while(it.hasNext()){
					if(it.next().equals(table)){
						HashMap<String,String> map1=map.get(table);
						value=map1.get(columnName);
						break;
					}
				}
			}
			sb.append(" value=\"");
			sb.append(value);
			sb.append("\" ");
						
		}

		sb.append("/>");
		return sb;
	}

	protected String toDefaultValueBySingleSql(String sql) throws Exception {// 从数据库读取单条数据
		IMacroDataComponent component = new MacroDataComponentSingleSql();
		return component.getValue(sql);
	}

	protected String toDefaultValueByMulSql(String sql) throws Exception {// 从数据库读取多条数据
		IMacroDataComponent component = new MacroDataComponentListSql(
				macroComponentService);
		return component.getValue(sql);
	}

	protected String toDefaultValue(String data) throws Exception {// 设置默认值，可以增加自定义数据类型。在这里可以扩展
		IMacroDataComponent component;
		if (data.equals("SYS_DATE")) {
			component = new MacroDataComponentDate();
		} else if (data.equals("SYS_DATE_YEAR")) {
			component = new MacroDataComponentDateYear();
		} else if (data.equals("SYS_DATE_YEARANDMONTH")) {
			component = new MacroDataComponentDateYearMonth();
		} else if (data.equals("SYS_DATE_MONTHANDDAY")) {
			component = new MacroDataComponentDateMonthDay();
		} else if (data.equals("SYS_TIME")) {
			component = new MacroDataComponentTime();
		} else if (data.equals("SYS_DATETIME")) {
			component = new MacroDataComponentDateTime();
		} else if (data.equals("SYS_WEEK")) {
			component = new MacroDataComponentWeek();
		} else {
			component = new MacroDataComponentDate();
			return null;
		}
		return component.getValue(data);
	}

	public List<HashMap<String, HashMap<String, String>>> getTableDatas() {
		return tableDatas;
	}

	public void setTableDatas(
			List<HashMap<String, HashMap<String, String>>> tableDatas) {
		this.tableDatas = tableDatas;
	}
}
